//
//  TravelMainViewController.m
//  TripGroup
//
//  Created by apple on 15/10/24.
//  Copyright © 2015年 lanou3g.com蓝鸥科技有限公司. All rights reserved.
//

#import "TravelMainViewController.h"
#import "PKRequestManager.h"
#import "TravelModel.h"
#import "TopFlowView.h"
#import "TravelTableViewController.h"
#import "TravelWebViewController.h"
#import "FMDatabase.h"
#import "Reachability.h"

@interface TravelMainViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView * topSrollView;// 顶端轮播图
@property (nonatomic, strong) UIPageControl * pageControl;
@property (nonatomic, strong) NSMutableArray *dataSourceArray;// 轮播图的数据源
@property (nonatomic, strong) TopFlowView *topFlowView;
@property (nonatomic, strong) TravelTableViewController *tableViewController;
@property (nonatomic, strong) UIButton *returnBtn;
@property (nonatomic, strong) FMDatabase *dataBase;// 数据库
@property (nonatomic, strong) Reachability *reach;

@end

@implementation TravelMainViewController

-(NSMutableArray *)dataSourceArray
{
    if (_dataSourceArray == nil) {
        self.dataSourceArray = [NSMutableArray array];
    }
    return _dataSourceArray;
}

- (void)viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated];
  self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];

    self.automaticallyAdjustsScrollViewInsets = NO;
    [self layoutTopview];
    [self requestData];
    
    UIImageView *backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"background.JPG"]];
    backgroundView.frame = CGRectMake(0, SCREEN_HEIGHT/3, SCREEN_WIDTH, SCREEN_HEIGHT*2/3);
    backgroundView.alpha = 0.5;
    [self.view addSubview:backgroundView];
    
    
    for (int i = 0; i < 4; i ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(50, SCREEN_HEIGHT/3+30+SCREEN_HEIGHT*i/7, SCREEN_WIDTH-100, SCREEN_HEIGHT/7);
        [button setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"trip%d.JPG",i]] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(toOtherTableView:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
    
    self.returnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.returnBtn.frame = CGRectMake(10, 20, 40, 30);
    self.returnBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.returnBtn setTitle:@"返回" forState:UIControlStateNormal];
//    [self.returnBtn setBackgroundImage:[UIImage imageNamed:@"returnreturn.png"] forState:UIControlStateNormal];
    [self.returnBtn setTitleColor:[UIColor colorWithRed:0.000 green:0.948 blue:0.626 alpha:1.000] forState:UIControlStateNormal];
    [self.returnBtn addTarget:self action:@selector(returnMainview) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.returnBtn];
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"Trip.db"];
    NSLog(@"%@",filePath);
    self.dataBase = [[FMDatabase alloc]initWithPath:filePath];
    if ([_dataBase open]) {
        [_dataBase executeUpdate:@"CREATE TABLE TopSrollView (descr text, image text, link text, post_time text, title text)"];
    }else
    {
        NSLog(@"数据库打开失败");
    }
    // 从数据库读取数据
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"SELECT * FROM TopSrollView"];
    while ([resultSet next]) {
        NSString *descr = [resultSet stringForColumn:@"descr"];
        NSString *image = [resultSet stringForColumn:@"image"];
        NSString *link = [resultSet stringForColumn:@"link"];
        NSString *post_time = [resultSet stringForColumn:@"post_time"];
        NSString *title = [resultSet stringForColumn:@"title"];


        TravelModel *model = [[TravelModel alloc]init];
        model.descr = descr;
        model.image = image;
        model.link = link;
        model.title = title;
        model.post_time = post_time;
        [self.dataSourceArray addObject:model];
    }
    [resultSet close];
    // 重新对scrollview上的View赋值
    if (self.dataSourceArray.count != 0) {
        [self configureWithTopview];
    }
    ///开启网络状况的监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [self.reach startNotifier]; //开始监听，会启动一个run loop
}
- (void)returnMainview
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
// 跳转到tableviewcontroller
- (void)toOtherTableView:(UIButton *)button
{
    int number = (int)(button.frame.origin.y - SCREEN_HEIGHT/3+30)*7/SCREEN_HEIGHT;
    if (number == 0) {
        self.tableViewController = [[TravelTableViewController alloc]init];
        self.tableViewController.typeStr = @"you";
        self.tableViewController.titleStr = @"旅游攻略";
        [self.navigationController pushViewController:self.tableViewController animated:YES];
    }else if (number == 1)
    {
        self.tableViewController = [[TravelTableViewController alloc]init];
        self.tableViewController.typeStr = @"point";
        self.tableViewController.titleStr = @"热门景点";
        [self.navigationController pushViewController:self.tableViewController animated:YES];
    }else if (number == 2)
    {
        self.tableViewController = [[TravelTableViewController alloc]init];
        self.tableViewController.typeStr = @"news";
        self.tableViewController.titleStr = @"旅游情报";
        [self.navigationController pushViewController:self.tableViewController animated:YES];
    }else
    {
        self.tableViewController = [[TravelTableViewController alloc]init];
        self.tableViewController.typeStr = @"hotel";
        self.tableViewController.titleStr = @"特色酒店";
        [self.navigationController pushViewController:self.tableViewController animated:YES];
    }

}
// 布局轮播图的视图
- (void)layoutTopview
{
    self.topSrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/3)];
    self.topSrollView.contentSize = CGSizeMake(SCREEN_WIDTH*5, SCREEN_HEIGHT/3);
    self.topSrollView.pagingEnabled = YES;
    self.topSrollView.alwaysBounceVertical = NO;
    self.topSrollView.bounces = NO;
    self.topSrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    self.topSrollView.showsHorizontalScrollIndicator = NO;
    self.topSrollView.delegate = self;
    [self.view addSubview:self.topSrollView];
    
    self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-20, SCREEN_HEIGHT/3-20, 40, 20)];
    self.pageControl.numberOfPages = 3;
    self.pageControl.currentPage = 0;
    self.pageControl.pageIndicatorTintColor = [UIColor grayColor];// 未选中的颜色
    self.pageControl.currentPageIndicatorTintColor = [UIColor colorWithRed:0.443 green:0.536 blue:1.000 alpha:1.000];
    [self.view addSubview:self.pageControl];
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.topSrollView.contentOffset.x == SCREEN_WIDTH||SCREEN_WIDTH*2||SCREEN_WIDTH*3) {
        self.pageControl.currentPage = (int)(self.topSrollView.contentOffset.x/SCREEN_WIDTH)-1;
    }
    
    if (self.topSrollView.contentOffset.x == 0) {
        self.topSrollView.contentOffset = CGPointMake(SCREEN_WIDTH*3, 0);
        _pageControl.currentPage = 2;
    }
    if (self.topSrollView.contentOffset.x == SCREEN_WIDTH*4) {
        self.topSrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
        _pageControl.currentPage = 0;
    }
}
// 网络请求部分
- (void)requestData
{
[PKRequestManager PKRequestManagerrequsetWithType:GET URLString:@"http://www.57yx.com/app/today.json" ParDIc:nil finish:^(NSData *data) {
    [_dataBase executeUpdate:@"DELETE FROM TopSrollView"];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
    NSArray *dataArr = dic[@"item_list"];
    for (NSDictionary *modelDic in dataArr) {
        TravelModel *model = [[TravelModel alloc]init];
        [model setValuesForKeysWithDictionary:modelDic];
        [self.dataSourceArray addObject:model];
        [_dataBase executeUpdate:@"INSERT INTO TopSrollView (descr, image, link, post_time, title) VALUES (?,?,?,?,?)",model.descr,model.image,model.link,model.post_time,model.title];
    }
    // 对轮播图上的view进行赋值
    [self configureWithTopview];
    
    } error:^(NSError *error) {
    NSLog(@"旅游轮播图数据请求失败%@",[error localizedDescription]);
    }];
}
- (void)configureWithTopview
{
    for (int i = 0; i <3; i++) {
        TravelModel *model = self.dataSourceArray[i];
        self.topFlowView = [[TopFlowView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*(i+1), 0, SCREEN_WIDTH, SCREEN_HEIGHT/3)];
        self.topFlowView.configureModel = model;
        [self.topFlowView.imgBtn addTarget:self action:@selector(didClickBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self.topSrollView addSubview:self.topFlowView];
    }
    
    TopFlowView *firstView = [[TopFlowView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/3)];
    firstView.configureModel = (TravelModel *)self.dataSourceArray[2];
    [firstView.imgBtn addTarget:self action:@selector(didClickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.topSrollView addSubview:firstView];
    
    TopFlowView *lastView = [[TopFlowView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*4, 0, SCREEN_WIDTH, SCREEN_HEIGHT/3)];
    lastView.configureModel = (TravelModel *)self.dataSourceArray[0];
    [lastView.imgBtn addTarget:self action:@selector(didClickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.topSrollView addSubview:lastView];
}
- (void)didClickBtn:(UIButton *)button
{
    TopFlowView *detailView = (TopFlowView *)button.superview;
    TravelWebViewController *travelWebVC = [[TravelWebViewController alloc]init];
    travelWebVC.webStr = detailView.configureModel.link;
    [self.navigationController pushViewController:travelWebVC animated:YES];
}

-(void)reachabilityChanged:(NSNotification*)note
{
    Reachability * reach = [note object];
    NSParameterAssert([reach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [reach currentReachabilityStatus];
    
    //    //用于检测是否是WIFI
    //    NSLog(@"%d",([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable));
    //    //用于检查是否是3G
    //    NSLog(@"%d",([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable));
    
    if (status == NotReachable) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"当前网络不可用,请检查您的网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
        NSLog(@"Notification Says Unreachable");
    }else if(status == ReachableViaWWAN){
        
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"您已连接移动网络,请考虑连接Wifi" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
    }else if(status == ReachableViaWiFi){
        
        //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"您已连接WIfi网络,请放心使用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        //        [alertView show];
        NSLog(@"连接上wifi");
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
